package com.jinkaimen.kqb.ui.activity.h5toapp;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.retrofit.RequestUtils;
import com.ht.baselibs.retrofit.bean.RequestParam;
import com.ht.baselibs.retrofit.converter.fastjson.FastJsonConverterFactory;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.AppAesUtil;
import com.ht.baselibs.utils.DateUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.api.FileApi;
import com.jinkaimen.kqb.bean.AuStepBean;
import com.jinkaimen.kqb.constant.HttpConfig;
import com.jinkaimen.kqb.http.ConsultInterceptor;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.thread.CompressPhotoThread;
import com.jinkaimen.kqb.thread.ValidateThread;
import com.jinkaimen.kqb.ui.activity.SelectLocationActivity;
import com.jinkaimen.kqb.ui.weiget.CustomPopwindow;
import com.jinkaimen.kqb.ui.weiget.DialogUtils;
import com.jinkaimen.kqb.utils.IDCardUtil;
import com.jinkaimen.kqb.utils.PermissionUtils;


import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;


/**
 * Created by lixuebo on 17/7/28.
 */

public class FillInformationActivity extends BaseActivity {
    private EditText mEtActivityIdentificationShopStep1ShortName;
    private RelativeLayout mRlActivityIdentificationShopStep1SelectLocation;
    private TextView mTvActivityIdentificationShopStep1Location;
    private EditText mEtActivityIdentificationShopStep1Address;
    private EditText mTvActivityIdentificationShopStep1OperatingCardNum;
    private ImageView mIvActivityIdentificationShopStep1Card;
    private EditText mEtActivityIdentificationShopStep4Name;
    private EditText mEtActivityIdentificationShopStep4Idcard;
    private EditText mEtActivityRegisterTel;
    private EditText mEtActivityLoginValidate;
    private TextView mTvActivityIdentificationShopStep1CardNum;
    private TextView mTvActivityLoginGetValidate;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/LICENCE.png";
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private static final int REQUEST_CODE_TAKE_PHOTO = 2;
    private static final int REQUEST_CODE_SEARCH_BANK = 3;
    private static final int REQUEST_CODE_TAKE_PHOTO_PIC = 5;
    private String mSelectCityCode;
    private String mSelectCityName;
    private String districtCode;
    private String branchCode;
    private static final int REQUEST_CODE_SEARCH_BANK_LOCATION = 4;
    private Uri imageUri;
    private String bankUseCode;
    private String bankNmae;
    private String url;
    private String picturePath;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

        mTitleBarView.setTitleText("填写资料");
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_fill_infor;
    }

    @Override
    protected void initChildView() {
        mEtActivityIdentificationShopStep1ShortName = (EditText) findViewById(R.id.et_activity_identification_shop_step1_short_name);
        mRlActivityIdentificationShopStep1SelectLocation = (RelativeLayout) findViewById(R.id.rl_activity_identification_shop_step1_select_location);
        mTvActivityIdentificationShopStep1Location = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_location);
        mEtActivityIdentificationShopStep1Address = (EditText) findViewById(R.id.et_activity_identification_shop_step1_address);
        mTvActivityIdentificationShopStep1OperatingCardNum = (EditText) findViewById(R.id.tv_activity_identification_shop_step1_operating_card_num);
        mIvActivityIdentificationShopStep1Card = (ImageView) findViewById(R.id.iv_activity_identification_shop_step1_card);
        mEtActivityIdentificationShopStep4Name = (EditText) findViewById(R.id.et_activity_identification_shop_step4_name);
        mEtActivityIdentificationShopStep4Idcard = (EditText) findViewById(R.id.et_activity_identification_shop_step4_idcard);
        mEtActivityRegisterTel = (EditText) findViewById(R.id.et_activity_register_tel);
        mEtActivityLoginValidate = (EditText) findViewById(R.id.et_activity_login_validate);
        mTvActivityIdentificationShopStep1CardNum = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_card_num);
        mTvActivityLoginGetValidate = (TextView) findViewById(R.id.tv_activity_login_get_validate);

    }

    @Override
    protected void initChildData() {

    }

    @Override
    protected void setChildViewListener() {
        mRlActivityIdentificationShopStep1SelectLocation.setOnClickListener(this);
        mIvActivityIdentificationShopStep1Card.setOnClickListener(this);
        mTvActivityLoginGetValidate.setOnClickListener(this);
        findViewById(R.id.tv_show_card_list).setOnClickListener(this);
        findViewById(R.id.btn_activity_identification_shop).setOnClickListener(this);
        findViewById(R.id.rl_branch_bank_name).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.rl_activity_identification_shop_step1_select_location://所在地
                ActivityUtils.startActivityForResult(this, SelectLocationActivity.class, SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY);
                break;

            case R.id.tv_show_card_list://支持银行
                showPop();

                break;
            case R.id.rl_branch_bank_name://选择支行
                String banNo = mTvActivityIdentificationShopStep1OperatingCardNum.getText().toString().trim();
                if (TextUtils.isEmpty(banNo)) {
                    UIUtils.showToast("请输入结算银行卡号");
                    return;
                }
                ActivityUtils.startActivityForResult(this, SelectLocationActivity.class, REQUEST_CODE_SEARCH_BANK);

                break;
            case R.id.iv_activity_identification_shop_step1_card://上传照片
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }

                break;
            case R.id.tv_activity_login_get_validate://获取验证码
                String bankdNo = mTvActivityIdentificationShopStep1OperatingCardNum.getText().toString();
                String name = mEtActivityIdentificationShopStep4Name.getText().toString();
                String idCardNo = mEtActivityIdentificationShopStep4Idcard.getText().toString();
                String mobile = mEtActivityRegisterTel.getText().toString();
                IDCardUtil.Result result = IDCardUtil.validateIDNum(idCardNo.toUpperCase());
                if (TextUtils.isEmpty(bankdNo)) {
                    UIUtils.showToast("请输入结算卡号");
                    return;
                }
                if (TextUtils.isEmpty(name)) {
                    UIUtils.showToast("请输入开户名");
                    return;
                }
                if (TextUtils.isEmpty(idCardNo)) {
                    UIUtils.showToast("请输入身份证号");
                    return;
                }

                if (!result.isMatch()) {
                    UIUtils.showToast("身份证号格式不正确,请重新输入");
                    return;
                }
                if (TextUtils.isEmpty(mobile)) {
                    UIUtils.showToast("请输入手机号");
                    return;
                }
                ApiManager.getApi().sendValue(
                        "HSS001035",
                        bankdNo,
                        name,
                        idCardNo,
                        mobile
                ).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        new ValidateThread(mHandler).start();
                        mTvActivityLoginGetValidate.setTextColor(Color.parseColor("#bebebe"));
                        mTvActivityLoginGetValidate.setEnabled(false);
                    }
                });

                break;
            case R.id.btn_activity_identification_shop://下一步
                String merchantName = mEtActivityIdentificationShopStep1ShortName.getText().toString().trim();
                String provinceCode = SharedPreferencesUtils.getString("province_code", "");
                String provinceName = SharedPreferencesUtils.getString("province_aname", "");
                String cityCode = SharedPreferencesUtils.getString("city_code", "");
                String cityName = SharedPreferencesUtils.getString("city_aname", "");
                String countyCode = SharedPreferencesUtils.getString("county_code", "");
                String countyName = SharedPreferencesUtils.getString("county_aname", "");
                String address = mEtActivityIdentificationShopStep1Address.getText().toString().trim();
                String bankNo = mTvActivityIdentificationShopStep1OperatingCardNum.getText().toString().trim();
                String bankPic = url;
                String accountName = mEtActivityIdentificationShopStep4Name.getText().toString().trim();
                String identity = mEtActivityIdentificationShopStep4Idcard.getText().toString().trim();
                String reserveMobile = mEtActivityRegisterTel.getText().toString().trim();
                String code = mEtActivityLoginValidate.getText().toString().trim();
                if (TextUtils.isEmpty(merchantName)) {
                    UIUtils.showToast("请输入商户名称");
                    return;
                }
                if (TextUtils.isEmpty(provinceCode)) {
                    UIUtils.showToast("请选择地区");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    UIUtils.showToast("请输入地址");
                    return;
                }
                if (TextUtils.isEmpty(bankNo)) {
                    UIUtils.showToast("请输入银行卡号");
                    return;
                }
                if (TextUtils.isEmpty(bankPic)) {
                    UIUtils.showToast("请上传银行卡正面照");
                    return;
                }
                if (TextUtils.isEmpty(accountName)) {
                    UIUtils.showToast("请输入开户名");
                    return;
                }
                if (TextUtils.isEmpty(identity)) {
                    UIUtils.showToast("请输入身份证号");
                    return;
                }
                IDCardUtil.Result result1 = IDCardUtil.validateIDNum(identity.toUpperCase());
                if (!result1.isMatch()) {
                    UIUtils.showToast("身份证号格式不正确,请重新输入");
                    return;
                }
                if (TextUtils.isEmpty(reserveMobile)) {
                    UIUtils.showToast("请输入银行卡预留手机号手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    UIUtils.showToast("请输入验证码");
                    return;
                }

                ApiManager.getApi().updateInfo(
                        "HSS001036",
                        merchantName,
                        provinceCode,
                        provinceName,
                        cityCode,
                        cityName,
                        countyCode,
                        countyName,
                        address,
                        bankNo,
                        bankPic,
                        accountName,
                        identity,
                        reserveMobile,
                        code,
                        branchCode,
                        bankNmae,
                        districtCode
                ).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        ActivityUtils.startActivityAndFinish(FillInformationActivity.this, UpdatePicActivity.class);
                    }
                });
                break;
        }

    }

    private void showPop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_show_bank_list, null);
        PopupWindow popWnd = new PopupWindow();
        popWnd.setContentView(contentView);
        popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWnd.setTouchable(true);

        popWnd.setBackgroundDrawable(
                getResources().

                        getDrawable(
                                R.mipmap.ic_service));
        backgroundAlpha(0.5f);

        // 设置好参数之后再show
        popWnd.setOutsideTouchable(true);
        popWnd.showAtLocation(mRlActivityIdentificationShopStep1SelectLocation, Gravity.CENTER, 0, 0);
        popWnd.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 100:
                mTvActivityLoginGetValidate.setText(msg.obj.toString());
                break;
            case 200:
                mTvActivityLoginGetValidate.setTextColor(Color.parseColor("#6284dd"));
                mTvActivityLoginGetValidate.setText("获取验证码");
                mTvActivityLoginGetValidate.setEnabled(true);
                break;
            case 300: //图片
                String path = "";
                switch ((int) msg.obj) {
                    case 0:
                        path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        break;
                    case 1:
                        path = picturePath;
                        break;
                    default:
                }
                Glide.with(this)//
                        .load(path)//
                        .skipMemoryCache(true)//
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(mIvActivityIdentificationShopStep1Card);
                HashMap<String, Object> requestDataMap = new HashMap<>();
                requestDataMap.put("fileA", "pic");
                File fileA = new File(path);
                String token = SharedPreferencesUtils.getString(ConsultInterceptor.ACCESS_TOKEN, "");
                String requestData = JSON.toJSONString(requestDataMap, false);
                try {
//                    requestData = AppAesUtil.encryptCBC_NoPaddingToBase64String(requestData, "utf-8", token.substring(0, 16), token.substring(16, 32));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LogUtils.error(requestData);
                Map<String, RequestBody> params = RequestUtils.createPartMap(
                        new RequestParam("serviceCode", "HSS001037"),
                        new RequestParam("accessToken", token),
                        new RequestParam("requestData", requestData),
                        new RequestParam(HttpConfig.GlobalParam.APP_TYPE, "android"),
                        new RequestParam(HttpConfig.GlobalParam.V, "v1.0.0"),
                        new RequestParam(HttpConfig.GlobalParam.TIME_STAMP, DateUtils.getCurrentTime()),
                        new RequestParam(HttpConfig.GlobalParam.DEVICE_ID, DeviceUtils.getDeviceId() + ""),
                        new RequestParam("fileA", fileA)

                );
                Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                retrofitBuilder.client(builder.build())
                        .baseUrl(HttpConfig.BASE_URL) //这里的baseUrl不用设置
                        .addConverterFactory(FastJsonConverterFactory.create())
                        .build()
                        .create(FileApi.class).uploadFileAndForm(params).enqueue(new NetCallBack<BaseGetBean>() {

                    private BaseGetBean baseGetBean;

                    @Override
                    protected void onSuccess(Call<BaseGetBean> call, Response<BaseGetBean> response) {
                        if (response != null) {
                            try {
                                baseGetBean = response.body();
                                UIUtils.showToast(baseGetBean.resultMessage);
                                Gson gson = new Gson();
                                AuStepBean auStepBean = gson.fromJson(baseGetBean.encryptDataResult, AuStepBean.class);
                                url = auStepBean.url;
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }


                    }

                    @Override
                    protected boolean isNullNeedCallback() {
                        return true;
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                hideLodingDialog();
                break;
        }
    }

    private void takePicture() {

        DialogUtils.createPopwindow(FillInformationActivity.this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                try {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);

//                    if (!file.getParentFile().exists()) {
//                        file.getParentFile().mkdirs();
//                    }
//                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//                            startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO_COUNTER);
                    imageUri = FileProvider.getUriForFile(FillInformationActivity.this, "com.jinkaimen.kqb.fileprovider", file);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);

                } catch (Exception e) {
                    UIUtils.showToast("无法启用系统相机");
                    e.printStackTrace();
                }

            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CODE_TAKE_PHOTO_PIC);
            }
        }).showAtBottom(mTitleBarView);


//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        //通过FileProvider创建一个content类型的Uri
//        imageUri = FileProvider.getUriForFile(this, "com.jinkaimen.kqb.fileprovider", file);
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
//        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
//        startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY:
                    mSelectCityCode = data.getStringExtra("cityCode");
                    if (mSelectCityCode != null) {
                        mSelectCityName = data.getStringExtra("cityName") + "/" + data.getStringExtra("areaName");
                        mTvActivityIdentificationShopStep1Location.setText(mSelectCityName);
                    }
                    break;
                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    showLoadingDialog();
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_PIC:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    showLoadingDialog();
                    break;
                case REQUEST_CODE_SEARCH_BANK://搜索支行
                    districtCode = data.getStringExtra("cityCode");
                    String UseCode1 = data.getStringExtra("bankUseCode");
                    if (!TextUtils.isEmpty(UseCode1)) {
                        bankUseCode = UseCode1;
                    }
                    String bankNo = mTvActivityIdentificationShopStep1OperatingCardNum.getText().toString();
                    Bundle bundle = new Bundle();
                    bundle.putString("bankNo", bankNo);
                    ActivityUtils.startActivityForResult(this, SearchBankActivity.class, bundle, REQUEST_CODE_SEARCH_BANK_LOCATION);
                    break;
                case REQUEST_CODE_SEARCH_BANK_LOCATION://搜索支行
                    bankNmae = data.getStringExtra("bankName");
                    branchCode = data.getStringExtra("branchCode");
                    mTvActivityIdentificationShopStep1CardNum.setText(bankNmae);
                    break;
                default:
            }
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


}
